// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use anyhow::Error as AnyhowError;
use tauri::ipc::InvokeError;

// 1. 定义当前 crate 的新类型，包装 anyhow::Error
#[derive(Debug)]
struct TauriAnyhowError(AnyhowError);

// 2. 实现 From<anyhow::Error>，允许 ? 自动转换
impl From<AnyhowError> for TauriAnyhowError {
    fn from(err: AnyhowError) -> Self {
        TauriAnyhowError(err) // 直接包装原始错误
    }
}

// 3. 保持 Into<InvokeError> 实现，满足 Tauri IPC 要求
impl Into<InvokeError> for TauriAnyhowError {
  fn into(self) -> InvokeError {
    // 将内部的 anyhow::Error 转换为字符串，再转为 InvokeError
    InvokeError::from(format!("操作失败: {}", self.0))
  }
}

#[tauri::command]
fn greet(name: &str) -> String {
  format!("Hello, {}! You've been greeted from Rust!", name)
}

use mod_loader_lib::scan_steam_apps;
#[tauri::command]
fn scan_steam_apps() -> Result<scan_steam_apps::SteamAppInfo, TauriAnyhowError> {
  let games = scan_steam_apps::scan_steam_apps()?;
  Ok(games)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
  tauri::Builder::default()
    .plugin(tauri_plugin_opener::init())
    .invoke_handler(tauri::generate_handler![greet, scan_steam_apps])
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

fn main() {
  run()
}
